<template>
  <div class="recharge-container dark">
    <div class="header-section">
      <div class="module-title">购买积分</div>
      <el-button 
        type="primary" 
        :icon="Document" 
        @click="handleGoToConsumeRecords"
        class="record-btn"
      >
        消费记录
      </el-button>
    </div>
    
    <!-- 积分信息 -->
    <el-card class="balance-card">
      <div class="balance-info">
        <div class="balance-title">当前积分</div>
        <div class="balance-amount">{{ userBalance }} 积分</div>
      </div>
    </el-card>

    <!-- 购买数量选择 -->
    <el-card class="amount-card">
      <template #header>
        <div class="card-header">
          <span>选择购买数量</span>
        </div>
      </template>
      <div class="purchase-section">
        <div class="price-info">
          <div class="price-label">单价</div>
          <div class="price-value">¥1 / 1积分</div>
        </div>
        <div class="quantity-control">
          <div class="quantity-label">购买数量</div>
          <div class="quantity-input">
            <el-input-number
              v-model="quantity"
              :min="10"
              :max="10000"
              :step="1"
              :precision="0"
              class="quantity-input-number"
              @change="handleQuantityChange"
            />
          </div>
        </div>
        <div class="total-info">
          <div class="total-points">可获得积分：{{ quantity }}</div>
          <div class="total-price">总价：¥{{ quantity }}</div>
        </div>
      </div>
    </el-card>

    <!-- 支付方式 -->
    <el-card class="payment-card">
      <template #header>
        <div class="card-header">
          <span>支付方式</span>
        </div>
      </template>
      <div class="payment-method">
        <img src="https://res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png" alt="微信支付" class="payment-icon">
        <span class="payment-name">微信支付</span>
      </div>
    </el-card>

    <!-- 确认购买按钮 -->
    <div class="action-footer">
      <div class="payment-summary">
        <span class="summary-label">实付金额：</span>
        <span class="summary-amount">¥ {{ quantity }}</span>
      </div>
      <el-button 
        type="primary" 
        size="large" 
        :loading="loading"
        @click="handleRecharge"
      >
        立即购买
      </el-button>
    </div>

    <!-- 支付二维码弹窗 -->
    <el-dialog
      v-model="showQRCode"
      title="扫码支付"
      width="400px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="qrcode-container">
        <div class="order-info">
          <h3>{{ orderInfo.description }}</h3>
          <p>订单号：{{ orderInfo.order_no }}</p>
          <p class="amount">支付金额：¥{{ orderInfo.amount }}</p>
        </div>
        <div class="qrcode-wrapper">
          <div ref="qrcodeRef" class="qrcode"></div>
        </div>
        <div class="qrcode-tips">
          <p>请使用微信扫描二维码完成支付</p>
          <div class="polling-status">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>正在等待支付结果... ({{ currentPollCount }}/{{ maxPollCount }})</span>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeQRCode">取消支付</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { apiRequest, API_CONFIG } from '../../config/api'
import QRCode from 'qrcode'

const router = useRouter()

// 用户积分
const userBalance = ref(0)
// 购买数量
const quantity = ref(10)
const loading = ref(false)
// 二维码相关
const showQRCode = ref(false)
const qrcodeRef = ref(null)
const orderInfo = ref({
  order_no: '',
  points: 0,
  amount: 0,
  qrcode_data: '',
  description: ''
})
// 轮询相关
const pollTimer = ref(null)
const pollInterval = 3000 // 3秒轮询一次
const maxPollCount = 60 // 最多轮询60次（3分钟）
const currentPollCount = ref(0)

// 处理数量变化
const handleQuantityChange = (value) => {
  if (value < 10) {
    quantity.value = 10
    ElMessage.warning('购买数量不能少于10')
  } else if (value > 10000) {
    quantity.value = 10000
    ElMessage.warning('购买数量不能超过10000')
  }
}

// 获取用户积分
const getUserBalance = async () => {
  try {
    const response = await apiRequest('/points/balance', {
      method: 'GET'
    })
    if (response.code === 200) {
      userBalance.value = response.data.points
    }
  } catch (error) {
    console.error('获取积分失败:', error)
  }
}

// 生成二维码
const generateQRCode = async (qrcodeUrl) => {
  try {
    console.log('开始生成二维码，URL:', qrcodeUrl)
    console.log('URL类型:', typeof qrcodeUrl)
    console.log('URL长度:', qrcodeUrl?.length)
    
    if (!qrcodeUrl) {
      throw new Error('二维码URL为空')
    }
    
    await nextTick()
    console.log('DOM更新完成，检查qrcodeRef...')
    console.log('qrcodeRef.value:', qrcodeRef.value)
    
    if (qrcodeRef.value) {
      qrcodeRef.value.innerHTML = ''
      console.log('开始调用 QRCode.toCanvas')
      
      // 创建一个 canvas 元素
      const canvas = document.createElement('canvas')
      
      await QRCode.toCanvas(canvas, qrcodeUrl, {
        width: 200,
        height: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      })
      
      // 将 canvas 添加到容器中
      qrcodeRef.value.appendChild(canvas)
      console.log('二维码 Canvas 生成成功')
    } else {
      console.error('qrcodeRef.value 为空，DOM元素未找到')
      throw new Error('二维码容器未找到')
    }
  } catch (error) {
    console.error('Canvas 二维码生成失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    
    // 尝试备用方案：使用 SVG 方式
    try {
      console.log('尝试使用 SVG 方式生成二维码')
      if (qrcodeRef.value && qrcodeUrl) {
        const svgString = await QRCode.toString(qrcodeUrl, { 
          type: 'svg',
          width: 200,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#FFFFFF'
          }
        })
        qrcodeRef.value.innerHTML = svgString
        console.log('SVG 二维码生成成功')
        return
      }
    } catch (svgError) {
      console.error('SVG 二维码生成也失败:', svgError)
    }
    
    // 最后尝试：使用 Data URL 方式
    try {
      console.log('尝试使用 Data URL 方式生成二维码')
      if (qrcodeRef.value && qrcodeUrl) {
        const dataUrl = await QRCode.toDataURL(qrcodeUrl, {
          width: 200,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#FFFFFF'
          }
        })
        
        const img = document.createElement('img')
        img.src = dataUrl
        img.style.width = '200px'
        img.style.height = '200px'
        
        qrcodeRef.value.innerHTML = ''
        qrcodeRef.value.appendChild(img)
        console.log('Data URL 二维码生成成功')
        return
      }
    } catch (dataUrlError) {
      console.error('Data URL 二维码生成也失败:', dataUrlError)
    }
    
    // 所有方式都失败
    ElMessage.error('生成支付二维码失败，请重试')
    throw error
  }
}

// 检查支付状态
const checkOrderStatus = async () => {
  try {
    const response = await apiRequest(`/recharge/check_order_status?order_no=${orderInfo.value.order_no}`, {
      method: 'GET'
    })

    console.log('检查支付状态响应:', response) // 添加调试日志

    if (response.code === 200) {
      if (response.data.is_paid === true) {
        // 支付成功
        ElMessage.success('支付成功')
        clearPollTimer() // 清除轮询
        showQRCode.value = false // 关闭二维码弹窗
        getUserBalance() // 刷新用户积分
        return true
      }
    }
    return false
  } catch (error) {
    console.error('检查支付状态失败:', error)
    return false
  }
}

// 开始轮询支付状态
const startPolling = () => {
  currentPollCount.value = 0
  clearPollTimer() // 清除可能存在的旧定时器
  
  pollTimer.value = setInterval(async () => {
    currentPollCount.value++
    
    const isPaid = await checkOrderStatus()
    if (isPaid || currentPollCount.value >= maxPollCount) {
      clearPollTimer()
      if (!isPaid && currentPollCount.value >= maxPollCount) {
        ElMessage.warning('支付超时，请重新发起支付')
        showQRCode.value = false
      }
    }
  }, pollInterval)
}

// 清除轮询定时器
const clearPollTimer = () => {
  if (pollTimer.value) {
    clearInterval(pollTimer.value)
    pollTimer.value = null
  }
}

// 关闭二维码弹窗
const closeQRCode = () => {
  clearPollTimer()
  showQRCode.value = false
}

// 发起充值
const handleRecharge = async () => {
  if (loading.value) return
  loading.value = true
  
  try {
    const response = await apiRequest('/recharge/create_order', {
      method: 'POST',
      body: JSON.stringify({
        amount: quantity.value,
        points: quantity.value
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.code === 200) {
      orderInfo.value = {
        order_no: response.data.order_no,
        points: response.data.points,
        amount: response.data.amount,
        qrcode_data: response.data.qrcode_data,
        description: `购买 ${response.data.points} 积分`
      }
      
      showQRCode.value = true
      await nextTick()
      await generateQRCode(response.data.qrcode_data)
      startPolling() // 开始轮询支付状态
    } else {
      ElMessage.error(response.msg || '创建订单失败')
    }
  } catch (error) {
    console.error('发起充值失败:', error)
    ElMessage.error('发起充值失败，请重试')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取用户积分
onMounted(() => {
  getUserBalance()
})

// 跳转到消费记录
const handleGoToConsumeRecords = () => {
  router.push('/recharge/records')
}

// 组件卸载时清除定时器
onUnmounted(() => {
  clearPollTimer()
})
</script>

<style scoped>
.dark {
  background-color: #1a1a1a;
  color: #ffffff;
}

.recharge-container {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.module-title {
  font-size: 24px;
  font-weight: bold;
  color: #ffffff;
  margin: 0;
}

.record-btn {
  background-color: #409EFF;
  border: none;
}

.record-btn:hover {
  background-color: #66b1ff;
}

:deep(.el-card) {
  background-color: #2a2a2a;
  border: 1px solid #333333;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

:deep(.el-card__header) {
  border-bottom: 1px solid #333333;
  padding: 15px 20px;
}

.balance-info {
  text-align: center;
  padding: 20px 0;
}

.balance-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 12px;
}

.balance-amount {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
}

.card-header {
  font-weight: bold;
  color: #ffffff;
}

.purchase-section {
  padding: 20px;
}

.price-info, .quantity-control, .total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #333333;
}

.total-info {
  border-bottom: none;
  margin-top: 30px;
}

.price-label, .quantity-label {
  color: #909399;
}

.price-value {
  color: #409EFF;
  font-weight: bold;
}

.quantity-input {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.quantity-input-number {
  width: 200px;
}

:deep(.quantity-input-number .el-input__wrapper) {
  background-color: #23232a !important;
  box-shadow: 0 0 0 1px #333 inset !important;
}

:deep(.quantity-input-number .el-input__inner) {
  color: #ffffff !important;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

:deep(.quantity-input-number .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF inset !important;
}

:deep(.quantity-input-number .el-input-number__decrease),
:deep(.quantity-input-number .el-input-number__increase) {
  background-color: #409EFF !important;
  color: #ffffff !important;
  border-color: #409EFF !important;
}

:deep(.quantity-input-number .el-input-number__decrease:hover),
:deep(.quantity-input-number .el-input-number__increase:hover) {
  background-color: #66b1ff !important;
  border-color: #66b1ff !important;
}

:deep(.quantity-input-number .el-input-number__decrease.is-disabled),
:deep(.quantity-input-number .el-input-number__increase.is-disabled) {
  background-color: #2a2a2a !important;
  color: #666666 !important;
  border-color: #333333 !important;
}


.total-points {
  color: #67C23A;
  font-weight: bold;
}

.total-price {
  color: #409EFF;
  font-weight: bold;
  font-size: 20px;
}

.payment-method {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: #333333;
  border-radius: 8px;
}

.payment-icon {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.payment-name {
  color: #ffffff;
  font-size: 16px;
}

.action-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 24px;
  margin-top: 24px;
}

.payment-summary {
  font-size: 16px;
}

.summary-label {
  color: #909399;
}

.summary-amount {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

:deep(.el-button--primary) {
  background-color: #409EFF;
  border: none;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
}

:deep(.el-button--primary:active) {
  background-color: #3a8ee6;
}

:deep(.el-button--large) {
  padding: 16px 40px;
  font-size: 16px;
}

/* 二维码弹窗样式 */
:deep(.el-dialog) {
  background-color: #2a2a2a;
  border: 1px solid #333333;
}

:deep(.el-dialog__header) {
  background-color: #333333;
  border-bottom: 1px solid #444444;
}

:deep(.el-dialog__title) {
  color: #ffffff;
  font-weight: bold;
}

:deep(.el-dialog__body) {
  padding: 30px;
}

.qrcode-container {
  text-align: center;
}

.order-info {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #333333;
  border-radius: 8px;
}

.order-info h3 {
  margin: 0 0 12px 0;
  color: #ffffff;
  font-size: 18px;
  font-weight: bold;
}

.order-info p {
  margin: 8px 0;
  color: #cccccc;
  font-size: 14px;
}

.order-info .amount {
  color: #409EFF;
  font-size: 16px;
  font-weight: bold;
}

.qrcode-wrapper {
  display: flex;
  justify-content: center;
  margin: 24px 0;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  display: inline-block;
}

.qrcode {
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-tips {
  margin-top: 20px;
}

.qrcode-tips p {
  margin: 8px 0;
  color: #cccccc;
  font-size: 14px;
}

.qrcode-tips .tip-text {
  color: #909399;
  font-size: 12px;
}

.polling-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  color: #409EFF;
  font-size: 14px;
}

.polling-status .el-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #444444;
  background-color: #333333;
  padding: 16px 30px;
}
</style> 